{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "5.1. 二维卷积层.ipynb",
      "provenance": [],
      "collapsed_sections": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/chongzicbo/Dive-into-Deep-Learning-tf.keras/blob/master/5.1.%20%E4%BA%8C%E7%BB%B4%E5%8D%B7%E7%A7%AF%E5%B1%82.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xvOxGd-Y3vvE",
        "colab_type": "text"
      },
      "source": [
        "##5.1. 二维卷积层\n",
        "&emsp;&emsp;卷积神经网络（convolutional neural network）是含有卷积层（convolutional layer）的神经网络。本章中介绍的卷积神经网络均使用最常见的二维卷积层。它有高和宽两个空间维度，常用来处理图像数据。本节中，我们将介绍简单形式的二维卷积层的工作原理。\n",
        "\n",
        "###5.1.1. 二维互相关运算\n",
        "&emsp;&emsp;虽然卷积层得名于卷积（convolution）运算，但我们通常在卷积层中使用更加直观的互相关（cross-correlation）运算。在二维卷积层中，一个二维输入数组和一个二维核（kernel）数组通过互相关运算输出一个二维数组。 我们用一个具体例子来解释二维互相关运算的含义。如图5.1所示，输入是一个高和宽均为3的二维数组。我们将该数组的形状记为 3×3 或（3，3）。核数组的高和宽分别为2。该数组在卷积计算中又称卷积核或过滤器（filter）。卷积核窗口（又称卷积窗口）的形状取决于卷积核的高和宽，即 2×2 。图5.1中的阴影部分为第一个输出元素及其计算所使用的输入和核数组元素： 0×0+1×1+3×2+4×3=19 。\n",
        "<div align=center><img src=\"https://zh.gluon.ai/_images/correlation.svg\" width=\"300\"/></div>\n",
        "<center>图5.1 二维互相关运算</center>\n",
        "&emsp;&emsp;在二维互相关运算中，卷积窗口从输入数组的最左上方开始，按从左往右、从上往下的顺序，依次在输入数组上滑动。当卷积窗口滑动到某一位置时，窗口中的输入子数组与核数组按元素相乘并求和，得到输出数组中相应位置的元素。图5.1中的输出数组高和宽分别为2，其中的4个元素由二维互相关运算得出：\n",
        "$$\n",
        "\\begin{split}0\\times0+1\\times1+3\\times2+4\\times3=19,\\\\\n",
        "1\\times0+2\\times1+4\\times2+5\\times3=25,\\\\\n",
        "3\\times0+4\\times1+6\\times2+7\\times3=37,\\\\\n",
        "4\\times0+5\\times1+7\\times2+8\\times3=43.\\\\\\end{split}\n",
        "$$\n",
        "\n",
        "&emsp;&emsp;下面我们将上述过程实现在corr2d函数里。它接受输入数组X与核数组K，并输出数组Y。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6Gyb-FO90CnY",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import tensorflow as tf\n",
        "from tensorflow import keras"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Qj22NMxd0T3_",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "tf.enable_eager_execution()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KK9u44sE0Wqo",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "def corr2d(X,K):\n",
        "  h,w=tf.shape(K).numpy()\n",
        "  Y=tf.Variable(tf.zeros((tf.shape(X)[0].numpy()-h+1,tf.shape(X)[1].numpy()-w+1)))\n",
        "  for i in range(tf.shape(Y)[0]):\n",
        "    for j in range(tf.shape(Y)[1]):\n",
        "      tf.assign(Y[i,j],tf.reduce_sum(X[i:i+h,j:j+w]*K))\n",
        "  return Y"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1e-KO5il40QD",
        "colab_type": "text"
      },
      "source": [
        "&emsp;&emsp;我们可以构造图5.1中的输入数组X、核数组K来验证二维互相关运算的输出。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "aZLy1jwy1rr8",
        "colab_type": "code",
        "outputId": "5f3a3ffb-c97a-4505-f805-1449e1a1056e",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 67
        }
      },
      "source": [
        "X=tf.constant([[0, 1, 2], [3, 4, 5], [6, 7, 8]],dtype=tf.float32)\n",
        "K=tf.constant([[0, 1], [2, 3]],dtype=tf.float32)\n",
        "corr2d(X,K)"
      ],
      "execution_count": 25,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=\n",
              "array([[19., 25.],\n",
              "       [37., 43.]], dtype=float32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 25
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S2eM3Tay4-L5",
        "colab_type": "text"
      },
      "source": [
        "###5.1.2. 二维卷积层\n",
        "&emsp;&emsp;二维卷积层将输入和卷积核做互相关运算，并加上一个标量偏差来得到输出。卷积层的模型参数包括了卷积核和标量偏差。在训练模型的时候，通常我们先对卷积核随机初始化，然后不断迭代卷积核和偏差。\n",
        "\n",
        "&emsp;&emsp;下面基于corr2d函数来实现一个自定义的二维卷积层。在构造函数__init__里我们声明卷积核尺寸。前向计算函数call则是直接调用corr2d函数。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "p7vSeGiU3-8T",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "class Conv2D(keras.layers.Layer):\n",
        "  def __init__(self,kernel_size):\n",
        "    super(Conv2D,self).__init__()\n",
        "    self.kernel_size=kernel_size\n",
        "\n",
        "  def build(self,input_shape):\n",
        "    self.kernel=self.add_weight(shape=self.kernel_size,name='kernel')\n",
        "    self.built=True\n",
        "  \n",
        "  def call(self,inputs):\n",
        "    return corr2d(inputs,self.kernel)\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vaxJMMN45Yea",
        "colab_type": "text"
      },
      "source": [
        "&emsp;&emsp;卷积窗口形状为 $p×q$ 的卷积层称为 $p×q$ 卷积层。同样， $p×q$ 卷积或 $p×q$ 卷积核说明卷积核的高和宽分别为 $p$ 和 $q$ 。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zl_sWqkD142o",
        "colab_type": "code",
        "outputId": "7b2e03b5-f47f-43c2-fe6d-090b38d22ba9",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 67
        }
      },
      "source": [
        "conv2D=Conv2D(kernel_size=[2,2])\n",
        "conv2D(X)"
      ],
      "execution_count": 27,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'conv2d_4/Variable:0' shape=(2, 2) dtype=float32, numpy=\n",
              "array([[-2.0149508, -1.8182033],\n",
              "       [-1.4247085, -1.2279611]], dtype=float32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 27
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hOVDvuaN5mz8",
        "colab_type": "text"
      },
      "source": [
        "###5.1.3. 图像中物体边缘检测\n",
        "&emsp;&emsp;下面我们来看一个卷积层的简单应用：检测图像中物体的边缘，即找到像素变化的位置。首先我们构造一张 6×8 的图像（即高和宽分别为6像素和8像素的图像）。它中间4列为黑（0），其余为白（1）。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "QYWmK2DDL3Sh",
        "colab_type": "code",
        "outputId": "15cfa580-63b9-4008-f8a2-d7c73d563d3a",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 134
        }
      },
      "source": [
        "X=tf.Variable(tf.ones((6,8)))\n",
        "X=tf.assign(X[:,2:6],tf.zeros(tf.shape(X[:,2:6])))\n",
        "X"
      ],
      "execution_count": 28,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'UnreadVariable' shape=(6, 8) dtype=float32, numpy=\n",
              "array([[1., 1., 0., 0., 0., 0., 1., 1.],\n",
              "       [1., 1., 0., 0., 0., 0., 1., 1.],\n",
              "       [1., 1., 0., 0., 0., 0., 1., 1.],\n",
              "       [1., 1., 0., 0., 0., 0., 1., 1.],\n",
              "       [1., 1., 0., 0., 0., 0., 1., 1.],\n",
              "       [1., 1., 0., 0., 0., 0., 1., 1.]], dtype=float32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 28
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BcCZcdhH5uAd",
        "colab_type": "text"
      },
      "source": [
        "&emsp;&emsp;然后我们构造一个高和宽分别为1和2的卷积核K。当它与输入做互相关运算时，如果横向相邻元素相同，输出为0；否则输出为非0。下面将输入X和我们设计的卷积核K做互相关运算。可以看出，我们将从白到黑的边缘和从黑到白的边缘分别检测成了1和-1。其余部分的输出全是0。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ncKvagyHWq4v",
        "colab_type": "code",
        "outputId": "2001af0a-62e2-48c3-f4aa-d0cbeb75f317",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 134
        }
      },
      "source": [
        "K=tf.constant([[1,-1]],dtype=tf.float32)\n",
        "Y=corr2d(X,K)\n",
        "Y"
      ],
      "execution_count": 29,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'Variable:0' shape=(6, 7) dtype=float32, numpy=\n",
              "array([[ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
              "       [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
              "       [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
              "       [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
              "       [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
              "       [ 0.,  1.,  0.,  0.,  0., -1.,  0.]], dtype=float32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 29
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6c-LnhTo57-l",
        "colab_type": "text"
      },
      "source": [
        "&emsp;&emsp;由此，我们可以看出，卷积层可通过重复使用卷积核有效地表征局部空间。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "05VrPxu56AGs",
        "colab_type": "text"
      },
      "source": [
        "###5.1.4. 通过数据学习核数组\n",
        "&emsp;&emsp;最后我们来看一个例子，它使用物体边缘检测中的输入数据X和输出数据Y来学习我们构造的核数组K。我们首先构造一个卷积层，将其卷积核初始化成随机数组。接下来在每一次迭代中，我们使用平方误差来比较Y和卷积层的输出，然后计算梯度来更新权重。简单起见，这里的卷积层忽略了偏差。\n",
        "\n",
        "&emsp;&emsp;虽然我们之前构造了Conv2D类，但由于corr2d使用了对单个元素赋值（[i, j]=）的操作因而无法自动求梯度。下面我们使用Keras提供的Conv2D类来实现这个例子。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "_8EKUWGrW2St",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 437
        },
        "outputId": "a465b965-94c1-4b6a-90ed-f93a27a791b3"
      },
      "source": [
        "optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.01)\n",
        "conv2d=keras.layers.Conv2D(1,kernel_size=(1,2))\n",
        "X=tf.reshape(X,shape=[1,6,8,1])\n",
        "Y=tf.reshape(Y,shape=(1,6,7,1))\n",
        "for i in range(50):\n",
        "  loss=keras.losses.mean_squared_error\n",
        "  l=loss(conv2d(X),Y)\n",
        "  optimizer.minimize(lambda:loss(conv2d(X),Y),global_step=tf.train.get_or_create_global_step())\n",
        "  if(i+1) %2==0:\n",
        "    print('batch %d,loss %.3f'%(i+1,tf.reduce_sum(l).numpy()))"
      ],
      "execution_count": 30,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "batch 2,loss 24.919\n",
            "batch 4,loss 14.023\n",
            "batch 6,loss 8.232\n",
            "batch 8,loss 4.863\n",
            "batch 10,loss 2.886\n",
            "batch 12,loss 1.718\n",
            "batch 14,loss 1.025\n",
            "batch 16,loss 0.613\n",
            "batch 18,loss 0.366\n",
            "batch 20,loss 0.219\n",
            "batch 22,loss 0.131\n",
            "batch 24,loss 0.079\n",
            "batch 26,loss 0.047\n",
            "batch 28,loss 0.028\n",
            "batch 30,loss 0.017\n",
            "batch 32,loss 0.010\n",
            "batch 34,loss 0.006\n",
            "batch 36,loss 0.004\n",
            "batch 38,loss 0.002\n",
            "batch 40,loss 0.001\n",
            "batch 42,loss 0.001\n",
            "batch 44,loss 0.000\n",
            "batch 46,loss 0.000\n",
            "batch 48,loss 0.000\n",
            "batch 50,loss 0.000\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gEzREh9V7Yeo",
        "colab_type": "text"
      },
      "source": [
        "&emsp;&emsp;可以看到，50次迭代后误差已经降到了一个比较小的值。现在来看一下学习到的核数组。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "flbP_DjrYJbv",
        "colab_type": "code",
        "outputId": "66759658-4b2f-4f88-da25-30c5b88020ba",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 84
        }
      },
      "source": [
        "conv2d.weights[0]"
      ],
      "execution_count": 31,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'conv2d_5/kernel:0' shape=(1, 2, 1, 1) dtype=float32, numpy=\n",
              "array([[[[ 0.9974407]],\n",
              "\n",
              "        [[-0.9974292]]]], dtype=float32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 31
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OmHi53Wo7ej4",
        "colab_type": "text"
      },
      "source": [
        "&emsp;&emsp;可以看到，学到的核数组与我们之前定义的核数组K较接近。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BpBSL0DJ7JID",
        "colab_type": "text"
      },
      "source": [
        "###5.1.5. 互相关运算和卷积运算\n",
        "&emsp;&emsp;实际上，卷积运算与互相关运算类似。为了得到卷积运算的输出，我们只需将核数组左右翻转并上下翻转，再与输入数组做互相关运算。可见，卷积运算和互相关运算虽然类似，但如果它们使用相同的核数组，对于同一个输入，输出往往并不相同。\n",
        "\n",
        "&emsp;&emsp;那么，你也许会好奇卷积层为何能使用互相关运算替代卷积运算。其实，在深度学习中核数组都是学出来的：卷积层无论使用互相关运算或卷积运算都不影响模型预测时的输出。为了解释这一点，假设卷积层使用互相关运算学出图5.1中的核数组。设其他条件不变，使用卷积运算学出的核数组即图5.1中的核数组按上下、左右翻转。也就是说，图5.1中的输入与学出的已翻转的核数组再做卷积运算时，依然得到图5.1中的输出。为了与大多数深度学习文献一致，如无特别说明，本书中提到的卷积运算均指互相关运算。\n",
        "\n",
        "###5.1.6. 特征图和感受野\n",
        "&emsp;&emsp;二维卷积层输出的二维数组可以看作是输入在空间维度（宽和高）上某一级的表征，也叫特征图（feature map）。影响元素 $x$ 的前向计算的所有可能输入区域（可能大于输入的实际尺寸）叫做 $x$ 的感受野（receptive field）。以图5.1为例，输入中阴影部分的四个元素是输出中阴影部分元素的感受野。我们将图5.1中形状为 2×2 的输出记为 $Y$ ，并考虑一个更深的卷积神经网络：将 $Y$ 与另一个形状为 2×2 的核数组做互相关运算，输出单个元素 $z$ 。那么， $z$ 在 $Y$ 上的感受野包括 $Y$ 的全部四个元素，在输入上的感受野包括其中全部9个元素。可见，我们可以通过更深的卷积神经网络使特征图中单个元素的感受野变得更加广阔，从而捕捉输入上更大尺寸的特征。\n",
        "\n",
        "&emsp;&emsp;我们常使用“元素”一词来描述数组或矩阵中的成员。在神经网络的术语中，这些元素也可称为“单元”。当含义明确时，本书不对这两个术语做严格区分。\n",
        "\n",
        "###5.1.7. 小结\n",
        "* 二维卷积层的核心计算是二维互相关运算。在最简单的形式下，它对二维输入数据和卷积核做互相关运算然后加上偏差。\n",
        "* 我们可以设计卷积核来检测图像中的边缘。\n",
        "* 我们可以通过数据来学习卷积核。"
      ]
    }
  ]
}